package virtorina.server.domain;

import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import virtorina.server.PMF;

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class Online implements Serializable {
	private static final long serialVersionUID = 1L;
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Long UserID;
	@Persistent
	private Integer RoomID;

	public Online(Long UserID, Integer RoomID) {
		this.UserID = UserID;
		this.RoomID = RoomID;
	}

	public Long getUserID() {
		return UserID;
	}

	public void setUserID(Long userID) {
		UserID = userID;
	}

	public Integer getRoomID() {
		return RoomID;
	}

	public void setRoomID(Integer roomID) {
		RoomID = roomID;
	}

	public static void addUserOnline(Long UserID, Integer RoomID) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Online o = new Online(UserID, RoomID);
		try {
			pm.makePersistent(o);
		} finally {
			pm.close();
		}
	}

	public static void removeUserOnline(Long UserID, Integer RoomID) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			 Query query = pm.newQuery(Online.class);
			    query.setFilter("UserID == uID");
			    query.declareParameters("Long uID");
			    query.deletePersistentAll(UserID);			
		} finally {
			pm.close();
		}
	}
	
	public static LinkedHashSet<Long> getidList(Integer RoomID){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery("select from " + Online.class.getName()
				+ " where RoomID == rID");
		q.declareParameters("Integer rID");
		List<Online> rslt = (List<Online>) q.execute(RoomID);
		pm.close();
		LinkedHashSet<Long> ids = new LinkedHashSet<Long>();
		for (Online o: rslt){
			ids.add(o.getUserID());
		}
		return ids;
	}
	
	public static void cleanRoon(Integer RoomID){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery("select from " + Online.class.getName()
				+ " where RoomID == rID");
		q.declareParameters("Integer rID");
		List<Online> rslt = (List<Online>) q.execute(RoomID);
		pm.deletePersistentAll(rslt);
		pm.close();
		
	}

}
